package com.gexiaobao.pigeon.ui.fragment.mine.training

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.model.bean.PigeonBean
import com.gexiaobao.pigeon.app.model.param.CreateTrainingParams
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentAddTrainingBinding
import com.gexiaobao.pigeon.ui.adapter.AddTrainingFlyAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.MyTrainingViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 17:58
 * @Describe    : 添加训放
 */
class FragmentAddTraining : BaseFragment<MyTrainingViewModel, FragmentAddTrainingBinding>() {

    private lateinit var loadsir: LoadService<Any>
    private val mAdapter: AddTrainingFlyAdapter by lazy { AddTrainingFlyAdapter(arrayListOf(),false) }
    private var pigeonData = ArrayList<PigeonBean.RingInfo>()
    private var invertList = ArrayList<PigeonBean.RingInfo>()
    private var muSelectedList = ArrayList<PigeonBean.RingInfo>()
    private val paramsList = arrayListOf<CreateTrainingParams.PigeonList>()
    private var mTrainingType = 0

    @SuppressLint("NotifyDataSetChanged")
    override fun initView(savedInstanceState: Bundle?) {

        mDatabind.includeBar.toolbar.initClose(getString(R.string.add_training)) {
            nav().navigateUp()
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 5f))
        )

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getPigeonList(true, "1")
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getPigeonList(true, "1")
        }

        mAdapter.addChildClickViewIds(R.id.train_fly_add_item_detail)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.train_fly_add_item_detail -> {
                    /** 跳转详情页面 */
                    nav().navigateAction(R.id.action_add_training_to_pigeon_detail, Bundle().apply {
                        putString("pigeonId", mAdapter.data[position].pigeonId.toString())
                        putString("type", "auto")
                        putBoolean("intentType", false)
                        putSerializable("pigeonData", mAdapter.data[position])
                    })
                }
            }
        }

        mAdapter.setOnMultipleChoiceClickListener(object : AddTrainingFlyAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, list: List<PigeonBean.RingInfo>) {
                /** 保存点击item选中的条目 */
                muSelectedList.clear()
                muSelectedList.addAll(list)
                /** 循环选中的item放入实体类中 */
                paramsList.clear()
                list.forEach {
                    val params = CreateTrainingParams.PigeonList(
                        pigeonId = it.pigeonId,
                        sex = it.sex,
                        featherColor = it.featherColor,
                        eyePattern = it.eyePattern,
                        ringSn = it.ringSn,
                        fosterName = it.name,
                        pigeonName = it.pigeonName,
                        ringId = it.ringId
                    )
                    paramsList.addAll(listOf(params))
                }
                if (paramsList.size == pigeonData.size) {
                    mDatabind.ivAddTrainingChecked.setImageResource(R.mipmap.checked)
                } else {
                    mDatabind.ivAddTrainingChecked.setImageResource(R.mipmap.unchecked)
                }
            }
        })
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        loadsir.showLoading()
        mViewModel.getPigeonList(true, "1")
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.llChooseAll, mDatabind.tvTrainFlyAddCommit) { it ->
            when (it) {
                mDatabind.llChooseAll -> chooseAllItem()
                mDatabind.tvTrainFlyAddCommit -> createTraining()
            }
        }
    }

    private fun createTraining() {
        if (invertList.isEmpty() && muSelectedList.isEmpty()) {
            RxToast.showToast(getString(R.string.please_choose_training_pigeon))
            return
        }
        showDialog()
    }

    private fun showDialog() {
        val dialog = RxDialogDefault(context)
        dialog.setLeftBtnContent(getString(R.string.train_fly_detail_detail_fragment_training_single))
        dialog.setRightBtnContent(getString(R.string.General_training))
        dialog.setTitle(getString(R.string.please_choose_training_type))
        dialog.setSureListener {
            mTrainingType = 2//普通
            val paramsBody = CreateTrainingParams(
                pigeonList = paramsList,
                trainingType = 2
            )
            mViewModel.createTraining(paramsBody)
            dialog.dismiss()
        }
        dialog.setCancelListener {
            mTrainingType = 1//单只
            val paramsBody = CreateTrainingParams(
                pigeonList = paramsList,
                trainingType = 1
            )
            mViewModel.createTraining(paramsBody)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun chooseAllItem() {
        if (invertList.size == pigeonData.size) {
            //清除选中的条目
            invertList.clear()
            mAdapter.setClear()
            mDatabind.ivAddTrainingChecked.setImageResource(R.mipmap.unchecked)
        } else {
            /** 获取全选之后的list数据 */
            invertList = mAdapter.setInvertSelection() as ArrayList<PigeonBean.RingInfo>
            /** 新的；list保存全选的数据 是否全部选中 */
            muSelectedList.clear()
            muSelectedList.addAll(invertList)

            mDatabind.ivAddTrainingChecked.setImageResource(R.mipmap.checked)
            /** 循环选中的数据放入实体类中 */
            paramsList.clear()
            invertList.forEach {
                val params = CreateTrainingParams.PigeonList(
                    pigeonId = it.pigeonId,
                    sex = it.sex,
                    featherColor = it.featherColor,
                    eyePattern = it.eyePattern,
                    ringSn = it.ringSn,
                    fosterName = it.name,
                    pigeonName = it.pigeonName,
                    ringId = it.ringId
                )
                paramsList.addAll(listOf(params))
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.pigeonData.observe(viewLifecycleOwner) {
            if (!it.listData.isNullOrEmpty()) {
                mDatabind.llChooseAll.visibility = View.VISIBLE
                pigeonData = it.listData
            } else {
                mDatabind.llChooseAll.visibility = View.GONE
            }
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }

        mViewModel.addTraining.observe(viewLifecycleOwner) {
            val id = it.id
            if (it.isSuccess) {
                nav().navigateAction(R.id.action_to_training_detail, Bundle().apply {
                    putInt("id", id)
                    putInt("type", 2)
                    putInt("trainingType", mTrainingType)
                    putInt("trainingStatus", 1)
                })
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }
}